package com.siha_back.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

public class StreamingResponseHandler {
    private final SseEmitter emitter;
    private final ObjectMapper mapper = new ObjectMapper();


    public StreamingResponseHandler(SseEmitter emitter) {
        this.emitter = emitter;
    }


    public void handleEvent(String jsonEvent) throws Exception {
        JsonNode root = mapper.readTree(jsonEvent);
        String eventType = root.path("event").asText();

        switch (eventType) {
            case "text_chunk":
                String text = root.path("data").path("text").asText();
                emitter.send(text); // 实时发送给前端
                break;

            case "workflow_finished":
                emitter.complete(); // 结束SSE连接
                break;

            case "error":
                emitter.completeWithError(new RuntimeException(root.toString()));
                break;
        }
    }
}
